package com.ly.mpayment.rest.recharge;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 敬恒api接口适配
 */
@Component
@Path("jingheng")
public class JingHengRest {

    Logger logger = Logger.getLogger(JingHengRest.class);

    @Autowired
    protected RechargeRest rechargeRest;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IDownShopProductService productService;

    @Autowired
    IDownRechargeFlowService flowService;

    /**
     * 敬恒提交订单
     userId	是	合作方用户编号(充值平台方提供)
     itemId	是	商品编号
     itemPrice	否	校验成本价格，单位厘；1元=1000厘
     checkItemFacePrice	是	商品面值 (单位厘，防止下单商品和面额不符)
     amt	否	目前只能充1笔
     uid	是	客户手机号，被充值号码
     serialno	是	合作方商户系统的流水号，全局唯一（不能重复使用）
     dtCreate	是	合作方交易时间(也可以是订单创建时间，格式为：yyyyMMddHHmmss)
     sign	是	sign=MD5(amt+checkItemFacePrice+dtCreate+itemId+itemPrice+serialno+uid+userId+privatekey);
     userId=2c92ce5478acb5590178b19120690002&
     itemId=2c92ce5478c160290178c90e4dc30025&
     checkItemFacePrice=50000&uid=13266667957&
     serialno=202104170029556007039939232417&
     dtCreate=20210417002955&
     sign=2a650d86c3370cc9238a00cd35258f4b
     * @param request
     * @return
     */
    @Path("commit")
    @GET
    public String recharge(@QueryParam("userId")String userId,@QueryParam("itemId")String itemId,
                           @QueryParam("checkItemFacePrice")String checkItemFacePrice,@QueryParam("uid")String uid,
                           @QueryParam("serialno")String serialno,@QueryParam("dtCreate")String dtCreate,
                           @QueryParam("sign")String sign , @Context HttpServletRequest request) {

        final String data = request.getQueryString();
        logger.info("commitjinegheng:"+data);
        if(StringUtils.isBlank(data)){
            //return ResultMessage.getFailt(null,"参数错误");
            return createCommitOrder("failed","10","参数错误!","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }
        final MultiMap multiMap = Util.parceString(data);
        if(!multiMap.containsKey("userId") || !multiMap.containsKey("itemId") || !multiMap.containsKey("checkItemFacePrice") || !multiMap.containsKey("uid")
                || !multiMap.containsKey("serialno") || !multiMap.containsKey("dtCreate") || !multiMap.containsKey("sign") ){
            return createCommitOrder("failed","10","参数错误!","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }
        DownShopInfo shop = shopService.findShopInfoForMaintenance(multiMap.getString("userId"));
        if(shop == null || shop.getUser().getUserstatus() == Config.productStatus[3]){
            //return ResultMessage.getFailt(ResultMessage.userCloseErrorJingheng);
            return createCommitOrder("failed","40","渠道关闭,禁止提单!","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }

        if(shop == null && StringUtils.isBlank(shop.getOrderCallAddress())){
            //return ResultMessage.getFailt(ResultMessage.userCloseErrorJingheng);
            return createCommitOrder("failed","40","渠道关闭,禁止提单!","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }

        //检查签名
        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId",multiMap.getString("userId"));
        jsonObject.put("itemId",multiMap.getString("itemId"));
        jsonObject.put("itemPrice",multiMap.getString("itemPrice"));
        jsonObject.put("checkItemFacePrice",multiMap.getString("checkItemFacePrice"));
        jsonObject.put("amt",multiMap.getString("amt"));
        jsonObject.put("uid",multiMap.getString("uid"));
        jsonObject.put("serialno",multiMap.getString("serialno"));
        jsonObject.put("dtCreate",multiMap.getString("dtCreate"));

        if(!multiMap.getString("sign").equals(MD5.md5(StringSort.doSignValue(jsonObject)+shop.getDownkey()).toLowerCase())){
            //return ResultMessage.getFailt(ResultMessage.searchSignErrorJingheng);
            return createCommitOrder("failed","11","sign错误","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }

        //检查IP
        if(!shop.getUser().getUseruuid().equals(CookieRedis.get("useruuid"))){
            if(!rechargeRest.checkIp(shop.getDownshopip(),request,true)){
                //return ResultMessage.getFailt(ResultMessage.shopNotexistErrorIPJingheng);
                return createCommitOrder("failed","12","商户不存在或者商户IP错误","",
                        "000000","","3", "",
                        "","话费0元","",
                        "");
            }
        }

        //检查订单是否存在
        if (flowService.findShopUUIDorder(multiMap.getString("serialno"),multiMap.getString("userId")) != null) {
            //return ResultMessage.getFailt(ResultMessage.shopNumErrorJingheng);
            return createCommitOrder("failed","23","商家订单号已经存在","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }

        //查询产品是否正常删除或者禁用的不可以提单
        DownShopProduct downProduct = this.productService.findByNotUseUUId(multiMap.getString("itemId"),multiMap.getString("userId"));
        if (downProduct == null || !String.valueOf((Integer.parseInt(multiMap.getString("checkItemFacePrice")) / 1000)).equals(downProduct.getDownfacevalue())) {
            //return ResultMessage.getFailt(ResultMessage.productDownErrorJingheng);
            return createCommitOrder("failed","44","未找到产品或面值错误","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }

        Mobile mobile = rechargeRest.checkMobile(multiMap.getString("uid").trim());
        if(mobile == null){
            //return ResultMessage.getFailt(ResultMessage.phoneNumErrorJingheng);
            return createCommitOrder("failed","25","未识别的号码","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }
        //如果产品为全国 则不检查省份
        if(!downProduct.getProvincialInformation().getProvincename().equals(Config.proCity)){
            //检查充值号段与产品号段是否匹配
            if(mobile != null && !mobile.getProvince().equals(downProduct.getProvincialInformation().getProvincename())){
                //return ResultMessage.getFailt(ResultMessage.provinceErrorJingheng);
                return createCommitOrder("failed","25","未识别的号码","",
                        "000000","","3", "",
                        "","话费0元","",
                        "");
            }
        }

        //检查充值号段是否禁止提单，如果是则不能保存订单
        if(mobile == null || mobile.getState() == Config.mobileState){
            //return ResultMessage.getFailt(ResultMessage.phoneNumErrorJingheng);
            return createCommitOrder("failed","25","产品或号段不正确","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }
        if(!StringUtils.isBlank(downProduct.getCityName()) && !mobile.getCity().equals(downProduct.getCityName())){
            // return ResultMessage.getFailt(ResultMessage.phoneNumErrorJingheng);
            return createCommitOrder("failed","25","产品或号段不正确","",
                    "000000","","3", "",
                    "","话费0元","",
                    "");
        }
        DownRechargeFlow flow = new DownRechargeFlow();
        Date date = DateUtils.getNowDate();
        flow.setCreatetime(date);

        flow.setDownreqid(multiMap.getString("serialno"));
        flow.setUserFlow(new User(multiMap.getString("userId")));
        flow.setRechargeamount(downProduct.getPrice());
        flow.setDowonphonenum(multiMap.getString("uid"));
        flow.setOperators(downProduct.getOperators().getOperatoruid());
        flow.setDownnotificationaddress(shop.getOrderCallAddress());
        if(shop.getUser().getUserstatus() != Config.productStatus[1] || downProduct.getStatus() != Config.productStatus[1]){
            flow.setStatus(Config.status[9] );
            //缓存订单
        }else{
            flow.setStatus(Config.status[5] );
            //订单到达
        }
        flow.setOperatorname(downProduct.getOperators().getOperatorname());
        flow.setBusCode(downProduct.getBusinessType().getBusCode());
        flow.setProvince(mobile.getProvince());
        flow.setCityName(mobile.getCity());
        flow.setCallStatus(Config.callStatus[0]);
        flow.setDownreqnum(1);
        flow.setDownendtimesec(Config.status[3]);
        flow.setDownShopProduct(downProduct);
        flow.setDiscount(downProduct.getDiscount());
        flow.setDiscountAmount(downProduct.getPrice().multiply(downProduct.getDiscount()));
        flow.setStatusremark(multiMap.getString("itemId"));
        //查询下游余额
        // 检查余额
        if(CookieRedis.get("checkbalance").equals(Config.onOff)){
            if (shop.getDownshopbalance().compareTo(flow.getDiscountAmount()) == -1) {
                //return ResultMessage.getFailt(ResultMessage.shopAmountErrorJingheng);
                return createCommitOrder("failed","42","余额不足","",
                        "000000","","3", "",
                        "","话费0元","",
                        flow.getDownreqid());
            }
        }
        //检查授信额度 如果有授信额度则可以提交订单，如果没有直接返回约不足，如果授信额度满了，直接返回余额不足
        if(flow.getDiscountAmount().compareTo(shop.getDownshopbalance()) == 1
                && ( flow.getDiscountAmount().compareTo(shop.getCredit()) == 1 )	){
            //return ResultMessage.getFailt(ResultMessage.shopAmountErrorJingheng);
            return createCommitOrder("failed","42","余额不足","",
                    "000000","","3", "",
                    "","话费0元","",
                    flow.getDownreqid());
        }
        //检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单
        if(shop.getDownshopbalance().compareTo(BigDecimal.ZERO) == -1 && Math.abs(shop.getDownshopbalance().intValue())
                >= shop.getCredit().intValue()){
            //return ResultMessage.getFailt(ResultMessage.shopAmountErrorJingheng);
            return createCommitOrder("failed","42","余额不足","",
                    "000000","","3", "",
                    "","话费0元","",
                    flow.getDownreqid());
        }
        try {
            flow = flowService.addDownrechargeflow(flow, shop);
            if(flow != null){
                if(shop.getUser().getUserstatus() == Config.productStatus[1] && downProduct.getStatus() == Config.productStatus[1]){
                    RechargeRest.orderQueue.add(flow);
                }else{
                    flow.setRemark("产品或者供货商未启用");
                    this.flowService.updateDownrechargeflow(flow);
                    logger.info("recharge_缓存订单:"+flow.getDowonphonenum());
                }

                JSONObject out = new JSONObject();
                out.put("oid", flow.getDownorderuuid());
                out.put("time", DateUtils.toLongDate(flow.getCreatetime()));
                //final String resultMs = ResultMessage.getSucceedOrder(ResultMessage.success, out.toString());
                logger.info("returnOrder:"+flow.getDowonphonenum()+","+out.toString());
                return createCommitOrder("success","00","交易成功",flow.getDiscountAmount().toString(),
                        "000000",flow.getDownorderuuid(),"3",Integer.parseInt(downProduct.getDownfacevalue()) * 1000 + "",
                        downProduct.getDownprouuid(),"话费"+downProduct.getDownfacevalue()+"元",Integer.parseInt(downProduct.getDownfacevalue()) * 1000 +"",
                        flow.getDownreqid());
            }else{
                logger.info("failt:"+flow.getDowonphonenum());
                return createCommitOrder("failed","30","交易失败","",
                        "000000","","3", "",
                        "","话费0元","",
                        flow.getDownreqid());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage()+":"+ flow == null ? "flow" : flow.getDowonphonenum());
            //return ResultMessage.getFailt(ResultMessage.systemErrorMessageJingheng);
            return createCommitOrder("failed","31","交易失败","",
                    "000000","","3", "",
                    "","话费0元","",
                    flow.getDownreqid());
        }
    }

    /**
     * <?xml version="1.0" encoding="UTF-8" ?>
     * <response>
     * <status>success</status>
     * <code>00</ code >
     * <desc>交易成功</desc>
     * <amount>29718</amount>  //交易总金额
     * <areaCode>330000</areaCode>  //省域代码
     * <bizOrderId>37088</bizOrderId>  //充值平台方流水号
     * <carrierType>3</carrierType>  //运营商类别
     * <itemFacePrice>3000</itemFacePrice>   //商品面值单位为厘
     * <itemId>136</itemId>   //商品编号
     * <itemName>全国移动话费3元</itemName>
     * <price>29718</price>  //商品单价
     * <serialno>123333</ serialno>   //合作方流水号
     * </response>
     * 创建提单返回结果
     * @return
     */
    public String createCommitOrder(String status, String code, String desc,
                                    String amount,String areaCode, String bizOrderId, String carrierType,
                                    String itemFacePrice,String itemId,String itemName,String price,String serialno) {
        Element response = DocumentHelper.createElement("response");

        Element statusX = DocumentHelper.createElement("status");
        statusX.setText(status);
        response.add(statusX);

        Element codeX = DocumentHelper.createElement("code");
        codeX.setText(code);
        response.add(codeX);

        Element descX = DocumentHelper.createElement("desc");
        descX.setText(desc);
        response.add(descX);

        Element amountX = DocumentHelper.createElement("amount");
        amountX.setText(amount);
        response.add(amountX);

        Element areaCodeX = DocumentHelper.createElement("areaCode");
        areaCodeX.setText(areaCode);
        response.add(areaCodeX);

        Element bizOrderIdX = DocumentHelper.createElement("bizOrderId");
        bizOrderIdX.setText(bizOrderId);
        response.add(bizOrderIdX);

        Element carrierTypex = DocumentHelper.createElement("carrierType");
        carrierTypex.setText(carrierType);
        response.add(carrierTypex);

        Element itemFacePricex = DocumentHelper.createElement("itemFacePrice");
        itemFacePricex.setText(itemFacePrice);
        response.add(itemFacePricex);

        Element itemIdx = DocumentHelper.createElement("itemId");
        itemIdx.setText(itemId);
        response.add(itemIdx);

        //-该节点每次请求时都要带
        Element itemNamex = DocumentHelper.createElement("itemName");
        itemNamex.setText(itemName);
        response.add(itemNamex);

        Element pricex = DocumentHelper.createElement("price");
        pricex.setText(price);
        response.add(pricex);

        Element serialnoX = DocumentHelper.createElement("serialno");
        serialnoX.setText(serialno);
        response.add(serialnoX);

        return response.asXML();
    }

    /**
     * <?xml version="1.0" encoding="UTF-8" ?>
     * <response>
     * <code>00</code>
     * <desc>交易成功</desc>
     * <status>success</status>
     * <data>
     * <amount>1000</amount> //交易金额
     * <amt>1</amt>     // 购买数量
     * <gmtCreate>2018-09-20 11:46:20</gmtCreate> // 订单创建时间
     * <gmtModify>2018-09-20 11:46:37</gmtModify>   // 交易完成时间
     * <id>1278648</id>     // 我方流水号
     * <itemId>216394</itemId>
     * <outOrderNo>2718092011462717</outOrderNo> //卡号、充值凭证 非必传
     * <vacherType >5</vacherType > //凭证类型 非必传
     * <serialno>1537415178903</serialno>   // 合作方流水号
     * <status>2</status> // 0或者1处理中 2成功3失败 4充值锁定中 (也是处理中) 9未确认
     * <statusDesc>成功</statusDesc>
     * </data>
     * </response>
     * @return
     */
    @Path("queryOrder")
    @GET
    public synchronized String queryOrder(@QueryParam("userId")String userId,@QueryParam("serialno")String serialno,
                                          @QueryParam("sign")String sign
            , @Context HttpServletRequest request) {
        //logger.info("jingheng_queryOrder:" + userId + ",serialno:"+serialno+",sign:"+sign);
        final String data = request.getQueryString();
        logger.info("jingheng_queryOrder:"+data);
        if(StringUtils.isBlank(data)){
            return createQueryOrder("failed","10","参数错误","",
                    "000000","","3", "",
                    "","话费0元","",
                    "","");
        }
        final MultiMap multiMap = Util.parceString(data);
        if(!multiMap.containsKey("userId") || !multiMap.containsKey("serialno") || !multiMap.containsKey("sign")){
            return createQueryOrder("failed","10","参数错误!","",
                    "000000","","3", "",
                    "","话费0元","",
                    "","");
        }

        DownShopInfo shop = shopService.findShopInfoByUuid(multiMap.getString("userId"));
        if (shop != null) {
            if (rechargeRest.checkIp(shop.getDownshopip(), request, true)) {
                // sign=MD5(serialno+userId+privatekey);
                final JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId",multiMap.getString("userId"));
                jsonObject.put("serialno",multiMap.getString("serialno"));
                jsonObject.put("sign",multiMap.getString("sign"));
                if (multiMap.getString("sign").equals(MD5.md5(StringSort.doSignValue(jsonObject)+shop.getDownkey()))) {
                    DownRechargeFlow flow = this.flowService.findShopUUIDorder(multiMap.getString("serialno"),multiMap.getString("userId"));
                    if (flow != null) {
                        JSONObject out = new JSONObject();
                        // 状态 0 删除 1 充值中 2 充值成功 3充值失败 4成功后取消的订单 5订单达到 6退款成功
                        // 7 退款失败 8失败后取消的订单 9 订单发送到上游失败
                        out.put("orderNum", flow.getDownorderuuid());
                        out.put("oid", flow.getDownreqid());
                        out.put("createtime", DateUtils.toLongDate(flow.getCreatetime()));
                        out.put("status", flow.getStatus());
                        out.put("msg", flow.getRemark());
                        logger.info("queryOrder:" + out.toString());
                        return createQueryOrder("success","00","查询成功!",(Integer.parseInt(flow.getDownShopProduct().getDownfacevalue()) * 1000)+"",
                                DateUtils.toLongDate(flow.getCreatetime()),
                                flow.getDownendtime() == null ? "" : DateUtils.toLongDate(flow.getDownendtime()),flow.getDownorderuuid()
                                ,
                                "",
                                flow.getRemark() == null ? "" : flow.getRemark(),"话费"+flow.getDownShopProduct().getDownfacevalue()+"元",flow.getDownreqid(),
                                flow.getStatus()+"",flow.getRemark() == null ? "" : flow.getRemark());
                    } else {
                        //return ResultMessage.getFailt(ResultMessage.orderNot);
                        return createQueryOrder("failed","50","查询异常,人工!","",
                                "000000","","3", "",
                                "","话费0元","",
                                "","");
                    }
                }
                //return ResultMessage.getFailt(ResultMessage.shopNotexistErrorIPJingheng);
                return createQueryOrder("failed","12","白名单错误!","",
                        "000000","","3", "",
                        "","话费0元","",
                        "","");
            } else {
                return createQueryOrder("failed","10","白名单错误!","",
                        "000000","","3", "",
                        "","话费0元","",
                        "","");
            }
        }
        return createQueryOrder("failed","10","通道状态错误!","",
                "000000","","3", "",
                "","话费0元","",
                "","");

    }

    /**
     * <?xml version="1.0" encoding="UTF-8" ?>
     * <response>
     * <code>00</code>
     * <desc>交易成功</desc>
     * <status>success</status>
     * <data>
     * <amount>1000</amount> //交易金额
     * <amt>1</amt>     // 购买数量
     * <gmtCreate>2018-09-20 11:46:20</gmtCreate> // 订单创建时间
     * <gmtModify>2018-09-20 11:46:37</gmtModify>   // 交易完成时间
     * <id>1278648</id>     // 我方流水号
     * <itemId>216394</itemId>
     * <outOrderNo>2718092011462717</outOrderNo> //卡号、充值凭证 非必传
     * <vacherType >5</vacherType > //凭证类型 非必传
     * <serialno>1537415178903</serialno>   // 合作方流水号
     * <status>2</status> // 0或者1处理中 2成功3失败 4充值锁定中 (也是处理中) 9未确认
     * <statusDesc>成功</statusDesc>
     * </data>
     * </response>
     * @return
     */
    public String createQueryOrder(String status, String code, String desc,
                                   String amount,String gmtCreate, String gmtModify, String id,
                                   String itemId,String outOrderNo,String vacherType,String serialno,String statusData,String statusDesc) {
        Element response = DocumentHelper.createElement("response");

        Element statusX = DocumentHelper.createElement("status");
        statusX.setText(status);
        response.add(statusX);

        Element codeX = DocumentHelper.createElement("code");
        codeX.setText(code);
        response.add(codeX);

        Element descX = DocumentHelper.createElement("desc");
        descX.setText(desc);
        response.add(descX);

        Element dataX = DocumentHelper.createElement("data");

        Element amountX = DocumentHelper.createElement("amount");
        amountX.setText(amount);
        dataX.add(amountX);

        Element amtX = DocumentHelper.createElement("amt");
        amtX.setText("1");
        dataX.add(amtX);

        Element gmtCreatex = DocumentHelper.createElement("gmtCreate");
        gmtCreatex.setText(gmtCreate);
        dataX.add(gmtCreatex);

        Element gmtModifyX = DocumentHelper.createElement("gmtModify");
        gmtModifyX.setText(gmtModify);
        dataX.add(gmtModifyX);

        Element idX = DocumentHelper.createElement("id");
        idX.setText(id);
        dataX.add(idX);

        Element itemIdX = DocumentHelper.createElement("itemId");
        itemIdX.setText(itemId);
        dataX.add(itemIdX);

        Element outOrderNoX = DocumentHelper.createElement("outOrderNo");
        outOrderNoX.setText(outOrderNo);
        dataX.add(outOrderNoX);

        Element vacherTypeX = DocumentHelper.createElement("vacherType");
        vacherTypeX.setText(vacherType);
        dataX.add(vacherTypeX);

        Element serialnoX = DocumentHelper.createElement("serialno");
        serialnoX.setText(serialno);
        dataX.add(serialnoX);

        Element statusDataX = DocumentHelper.createElement("status");
        statusDataX.setText(statusData);
        dataX.add(statusDataX);

        Element statusDescX = DocumentHelper.createElement("statusDesc");
        statusDescX.setText(statusDesc);
        dataX.add(statusDescX);

        response.add(dataX);
        return response.asXML();
    }


    @Path("searchAmount")
    @GET
    public synchronized String searchAmount(@QueryParam("userId")String userId,@QueryParam("sign")String sign
            , @Context HttpServletRequest request) {
        final String data = request.getQueryString();
        logger.info("jingheng_searchAmount:"+data);
        if(StringUtils.isBlank(data)){
            return createSearchAmount("failed","10","参数错误!","0");
        }
        final MultiMap multiMap = Util.parceString(data);
        if(!multiMap.containsKey("userId") || !multiMap.containsKey("sign")){
            return createSearchAmount("failed","10","参数错误!","0");
        }

        DownShopInfo shop = shopService.findShopInfoByUuid(multiMap.getString("userId"));
        if (shop != null) {
            if (rechargeRest.checkIp(shop.getDownshopip(), request, true)) {
                final JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId",multiMap.getString("userId"));
                jsonObject.put("sign",multiMap.getString("sign"));
                if (multiMap.getString("sign").equals(MD5.md5(StringSort.doSignValue(jsonObject)+shop.getDownkey()))) {
                    jsonObject.put("success", "success");
                    jsonObject.put("balance", shop.getDownshopbalance().multiply(new BigDecimal(1000)));
                    logger.info("searchAmount:" + jsonObject.toString());
                    return createSearchAmount("success","00","查询成功!", shop.getDownshopbalance().multiply(new BigDecimal(1000)).toString());
                }
                return createSearchAmount("failed","10","签名错误!","0");
            } else {
                return createSearchAmount("failed","11","ip白名单错误!","0");
            }
        }
        return createSearchAmount("failed","10","通道状态错误!","0");
    }

    /**
     * <?xml version="1.0" encoding="UTF-8" ?>
     * <response>
     * <status>success</status>
     * <desc>交易成功</desc>
     * <code>00</ code >
     * <balance>100000</balance>  //以厘为单位   100元
     * </response>
     * @param status
     * @param code
     * @param desc
     * @param balance
     * @return
     */
    public String createSearchAmount(String status, String code, String desc,String balance) {
        Element response = DocumentHelper.createElement("response");

        Element statusX = DocumentHelper.createElement("status");
        statusX.setText(status);
        response.add(statusX);

        Element codeX = DocumentHelper.createElement("code");
        codeX.setText(code);
        response.add(codeX);

        Element descX = DocumentHelper.createElement("desc");
        descX.setText(desc);
        response.add(descX);

        Element balanceX = DocumentHelper.createElement("balance");
        balanceX.setText(balance);
        response.add(balanceX);

        return response.asXML();
    }

}
